#include "server.h"

int regisUser(int netfd, MYSQL* mysql){
    
    //接收用户名和密码
    char userInfo[1024] = {0};
    train_t train;
    int length;
    int ret = recv(netfd, &length, sizeof(length), 0);
    ret = recv(netfd, userInfo, length, 0);
    printf("regis first receive userinfo %s\n", userInfo);
    //char userInfo[] = "testuser/testpsw";
    //分离用户名和密码
    char *username = strtok(userInfo, "/");
    char *password = strtok(NULL, "/");
    
    char* salt = generateStr();
    char* cryPassword = crypt(password, salt);
    //printf("cry Password = %s\n", cryPassword);
    char sql[1024] = "insert into user (username, salt, password) values ( '";
    strcat(sql, username);
    strcat(sql, "', '");
    strcat(sql, salt);
    strcat(sql, "', '");
    strcat(sql, cryPassword);
    strcat(sql, "');");

    int qret = mysql_query(mysql, sql);
    if(qret != 0){
        fprintf(stderr, "mysql_query:%s\n", mysql_error(mysql));
        printf("%d netfd regis error.\n",netfd);
        ret = 0;
        send(netfd, &ret, sizeof(ret), MSG_NOSIGNAL);
        return -1;
    }else if(qret == 0){
        char dirPath[1024] = "./pan/";
        mkdir(dirPath, 0755);
        strcat(dirPath, username);
        printf("dirPath = %s\n", dirPath);
        int retmk = mkdir(dirPath, 0777);
        if(retmk == 0){
            printf("create %s root dir success.\n", username);
        }else if(retmk == -1){
            printf("create %s root dir failed.\n", username);
            return -1;
        }
        char sql1[1024] = "insert into file (filename, type, pre_id, user, path, tomb, md5) values('";
        strcat(sql1, username);
        strcat(sql1, "', '");
        strcat(sql1, "d', '-1', '");
        strcat(sql1, username);
        strcat(sql1, "', 'pan/");
        strcat(sql1, username);
        strcat(sql1, "', '0', '0');");
        printf("sq1 = %s\n", sql1);
        qret = mysql_query(mysql, sql1);
        ret = 1;
        send(netfd, &ret, sizeof(ret), MSG_NOSIGNAL);
        printf("%d netfd regis success.\n",netfd);
        return 1;
    }
}
